<template>
  <div class="default-auditor-select">
    <div v-if="page === -1" class="tab-box">
      <div class="tab-btn" @click="tabClick(1, '按组织结构选择')"><img :src="auditorBtnIcon" >按组织结构选择</div>
      <!-- v3.2.8 隐藏按角色选择 -->
      <!-- <div class="tab-btn" @click="tabClick(2, '按角色选择')"><img :src="auditorBtnIcon" >按角色选择</div> -->
      <!-- <div class="tab-btn"><img :src="auditorBtnIcon" >产品组</div> -->
      <div v-for="(item, index) in belongStruct" :key="index + 3" class="tab-btn" @click="tabClick(index + 3, getLastDept(item).departmentName)">
        <img :src="auditorBtnIcon" >
        {{ getLastDept(item).departmentName }}
      </div>
      <div v-if="initDiyUserList && initDiyUserList.length">
        <dept-select-list :max="max" :breadcrumb-data="initDiyUserList" :select-items.sync="selectItemIds" :select-users.sync="_selectedAuditors" only-show-user />
      </div>
    </div>
    <div v-else class="content-box">
      <div class="content-header" @click="backFirst">
        <i class="el-icon-arrow-left" />
        {{ contentTitle }}
      </div>
      <div class="content-item-box">
        <dept-select-list v-if="contentType === 1" :max="max" :breadcrumb-data="defalutStruct" :select-items.sync="selectItemIds" :select-users.sync="_selectedAuditors" />
        <!-- <character-auditor-select v-if="contentType === 2" :select-items.sync="selectItemIds" :select-users.sync="_selectedAuditors" /> -->
        <template v-for="(item, index) in belongStruct">
          <dept-select-list
            v-if="contentType === (index + 3)"
            :key="index"
            :max="max"
            :breadcrumb-data="returnTargetDept(item)"
            :select-items.sync="selectItemIds"
            :select-users.sync="_selectedAuditors" />
        </template>
      </div>
    </div>
  </div>
</template>
<script>
import auditorBtnIcon from '@/assets/auditor_btn_icon.png';
import { allDeptlist } from '@/api/select';
import DeptSelectList from './deptSelectList';
import CharacterAuditorSelect from './characterAuditorSelect';
import { mapState } from 'vuex';
export default {
  name: 'DefaultAuditorSelect',
  components: { DeptSelectList, CharacterAuditorSelect },
  props: {
    selectedAuditors: { // 最终选择的审批人
      type: Array,
      default: () => {
        return [];
      }
    },
    tagSelecteds: { // 显示的tag数据
      type: Array,
      default: () => {
        return [];
      }
    },
    max: {
      type: Number,
      default: 50
    },
    initDiyUserList: {
      // 自定义人员如果选择了“允许选择其他人选项”，则在选择用户的第一页展示默认选中的那些人
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      auditorBtnIcon,
      page: -1,
      contentType: 0,
      contentTitle: '',
      defalutStruct: [],
      // selectItemIds: [], // 所选择的人员或者部门的id
      selectUsers: [], // 所选择的人员
      belongStruct: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    selectItemIds: { // 所选择的人员或者部门的id
      get() {
        return this.tagSelecteds;
      },
      set(val) {
        this.$emit('update:tagSelecteds', val);
      }
    },
    _selectedAuditors: {
      get() {
        return this.selectedAuditors;
      },
      set(val) {
        this.$emit('update:selectedAuditors', val);
      }
    }
  },
  created() {
    this.getAllDeptList();
  },
  methods: {
    // 获取用户所属部门的最后一级
    getLastDept(item) {
      let lastIndex = 0;
      if (item.length > 0) {
        lastIndex = item.length - 2; // 因为我们根据用户id检索出来的树路径我们只需要到倒数第二层 所以 -2
      }
      return item[lastIndex];
    },
    // 去除用户用户自己的那个层级的部门结构
    returnTargetDept(item) {
      const temp = JSON.parse(JSON.stringify(item));
      if (item.length > 1) {
        const lastIndex = item.length - 1;
        temp.splice(lastIndex, 1);
        return temp;
      } else {
        return temp;
      }
    },
    tabClick(type, title) {
      this.page = 1;
      this.contentType = type;
      this.contentTitle = title;
    },
    backFirst() {
      this.page = -1;
    },
    getAllDeptList() {
      allDeptlist().then(res => {
        if (res.code === 200) {
          const root = {
            departmentName: '飞博共创',
            children: res.data,
            isDepartment: 1
          };
          this.defalutStruct = [root];
          this.belongStruct = this.findPath(root, this.userInfo.id);
        }
      });
    },
    // 根据根节点找出路径的函数 isRoot 是否要到达根节点
    findPath(root, id) {
      // 1. 设置结果集
      const result = [];
      // 2. 深度优先搜索：root -> 树；path -> 路径；targetId -> 要寻找的目标id
      const recursion = (root, path, targetId) => {
        // 2.1 终止条件
        if (!root) {
          return;
        }
        // 2.2 路径添加一个元素
        path.push(root);
        if (!(root.children && root.children.length > 0)) {
          // console.log(root.userId, targetId);
          if (root.userId === targetId) {
            const temp = JSON.parse(JSON.stringify(path));
            result.push(temp);
          }
        } else {
          root.children.forEach(item => {
            recursion(item, path, targetId);
          });
        }
        path.pop();
      };
      recursion(root, [], id);
      return result;
    }
  }
};
</script>
<style lang="scss" scoped>
.tab-box {
  padding-left: 19px;
  height: 458px;
  @include scrollBar($width: 4px);
  .tab-btn {
    img {
      width: 17px;
      height: 17px;
      margin-right: 16px;
    }
    cursor: pointer;
    display: flex;
    margin-bottom: 32px;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
    color: #333;
  }
}
.content-header {
  padding-left: 22px;
  cursor: pointer;
  display: flex;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  i {
    color: #999;
    margin-right: 12px;
  }
}
</style>
